package com.design_pattern.prototype;

/**
 * 原型模式
 * java自带   克隆  就是 原型模式   对一个对象进行克隆成一个互相的属性独立存在，互不干预的另一份对象
 * 浅克隆 只对基本属性进行独立克隆， 对引用属性内的值进行修改时，还是会使得两份数据互相受到影响
 * 深克隆  引用属性也需要递归实现克隆
 * <p>
 * 一般用于一个对象的属性已经确定，需要产生很多相同对象的时候
 */
public class Main {
    public static void main(String[] args) throws CloneNotSupportedException {
        Person person = new Person(10, "xiaoli", new Location("beijing"));
        Person clonePerson = (Person) person.clone();
        person.age = 88;
        person.name = "changeName";
        person.location.city = "changer";
        System.out.println(person);
        System.out.println(clonePerson);
    }

}

class Person implements Cloneable {
    int age;
    String name;
    Location location;

    public Person(int age, String name, Location location) {
        this.age = age;
        this.name = name;
        this.location = location;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        Person person = (Person) super.clone();
        person.location = (Location) location.clone();
        return person;
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", location=" + location +
                '}';
    }
}

class Location implements Cloneable {
    String city;

    public Location(String city) {
        this.city = city;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    public String toString() {
        return "Location{" +
                "city='" + city + '\'' +
                '}';
    }
}
